package com.lzc.springMvcPart;

import com.lzc.springMvcPart.annotation.Token;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 需要手动加入到HandlerMethodHandlerAdapter对象中
 */
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {

    // 是否支持该参数的解析
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Token token = parameter.getParameterAnnotation(Token.class);
        return token != null;
    }

    // 支持则执行该流程
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // 从请求头获取token信息返回
        String token = webRequest.getHeader("token");
        return token;
    }
}
